/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

/**
 *  Sets headers needed to enable file downloads in IE7 under https
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public final class DownloadFilter implements Filter {

    Logger log = Logger.getLogger(this.getClass());

    private FilterConfig config = null;

    public void init(FilterConfig config) 
	throws ServletException {

	this.config = config;
    }


    public void destroy() {
	this.config = null;
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	log.debug("DownloadFilter: Adding headers");

	try {
	    HttpServletResponse httpResponse = (HttpServletResponse)response;
	    HttpServletRequest httpRequest   = (HttpServletRequest)request;
	    
	    //get the filename
	    String command  = httpRequest.getRequestURI();
	    log.debug("           command: " + command);

	    String filename = command.substring( command.lastIndexOf("/") + 1 );
	    log.debug("          filename: " + filename);
	    
	    httpResponse.setContentType("application/octet-stream"); 
	    httpResponse.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
	    httpResponse.setHeader("Expires", "0");
	    httpResponse.setHeader("Pragma", "public");
	    httpResponse.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
	 
	} catch (Exception e) {
	    log.debug("Exception during DownloadFilter", e);

	}
   
	//forward on to other filters
	chain.doFilter(request, response);
    }

}
